<?php

class Workset_Controller_Action_Helper_FileDestination extends Zend_Controller_Action_Helper_Abstract {

    const MAX_DIR_INDEX = 100;
    const DIR_DEPTH = 2;
    const RAND_STEPS = 2;
    const DIR_MODE = 0777;

    function direct($path = null, $module = null) {
        if (is_string($module)) {
            if (null === $path) {
                $path = $module;
            } else {
                $path = trim($path, '\/');
                $path .= '/'.$module;
            }
        }

        return $this->mkDir($path);
    }

    function mkDir($path) {
        $path = $this->_getDir($path);
        $this->_mkDir($path);

        return $path;
    }

    protected function _getDir($basePath = null) {
		$path = array(mt_rand(1, self::MAX_DIR_INDEX));

        for ($i = 0; $i < self::DIR_DEPTH; $i++) {
            $ascii = '';
            for ($j = 0; $j < self::RAND_STEPS; $j++) {
                $ascii .= chr(mt_rand(97, 122));
            }
            $path[] = $ascii;
        }
        
        $path = array_reverse($path);
        $path = implode(DIRECTORY_SEPARATOR, $path);

        if (is_string($basePath) && $basePath) {
            $basePath = trim($basePath, '\/');
            $path = implode(DIRECTORY_SEPARATOR, array($basePath, $path));
        }
        
		return $path;
	}

    protected function _mkDir($path) {
        if (!is_dir($path)) {
            @mkdir($path, self::DIR_MODE, true);
        }
    }

}

?>